<template>
    <div>
        <div class="button-group">
            <el-button link type="primary" @click="handleBack">
                <el-icon>
                    <Back />
                </el-icon>
                返回
            </el-button>
            <el-button-group>
                <el-button type="primary" @click="O_Add(true)">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    新增审核问题
                </el-button>
            </el-button-group>
        </div>

        <!-- 表格 -->
        <el-table :data="P_Form.auditIssues" border style="width: 100%">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="status" label="审核状态">
                <template #default="{ row }">
                    <el-tag v-if="row.status == 0" type="info">待审核</el-tag>
                    <el-tag v-if="row.status == 1" type="success">已审核</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="issue" label="审核问题" />
            <el-table-column prop="close" label="是否关闭" />
            <el-table-column label="计划文件">
                <template #default="{ row }">
                    <el-button v-for="file in row.annexFiles" :key="file.uploadFileId" link type="primary"
                        @click="downloadFile(file)">
                        {{ file.uploadFileName }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="160">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleEdit(row)">详情</el-button>
                    <el-button link type="success" v-if="!row.status" @click="handleExamine(row)">审核</el-button>
                    <el-button link type="danger" v-if="!row.status" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 抽屉表单 -->
        <el-drawer v-model="showDrawer" @open="handleDrawerOpen" :title="showupload ? '新增审核计划' : '审核计划详情'" size="600px">
            <el-form ref="qualityFormRef" :model="qualityForm" label-width="120px">
                <!-- <el-form-item label="是否关闭" prop="close"
                    :rules="[{ required: true, message: '请选择是否关闭', trigger: 'change' }]">
                    <el-radio-group v-model="qualityForm.close">
                        <el-radio value="YES">是</el-radio>
                        <el-radio value="NO">否</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                <el-form-item label="审核问题" prop="issue"
                    :rules="[{ required: true, message: '请输入审核问题', trigger: 'blur' }]">
                    <el-input v-model="qualityForm.issue" type="textarea" :rows="4" placeholder="请输入审核问题" />
                </el-form-item>

                <el-form-item label="计划文件" prop="files">
                    <div style="width: 100%">
                        <el-upload v-if="!qualityForm.status" class="upload-demo" ref="uploadRef" action="/api/upload"
                            :auto-upload="false" :on-success="handleUploadSuccess" :on-error="handleUploadError"
                            :on-change="handleFileChange" :before-upload="beforeUpload" multiple drag>
                            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                            <div class="el-upload__text">
                                将文件拖到此处，或<em>点击上传</em>
                            </div>
                            <template #tip>
                                <div class="el-upload__tip">
                                    <div>支持 任意类型 格式文件</div>
                                </div>
                            </template>
                        </el-upload>
                    </div>
                    <div v-if="qualityForm.annexFiles?.length">
                        <div v-for="file in qualityForm.annexFiles" :key="file.uploadFileId" class="file-info"
                            @click="downloadFile(file)">
                            <el-icon>
                                <Document />
                            </el-icon>
                            <span>{{ file.uploadFileName }}</span>
                        </div>
                    </div>
                </el-form-item>

                <div class="drawer-footer">
                    <el-button @click="showDrawer = false">取消</el-button>
                    <el-button type="primary" v-if="!qualityForm.status" @click="handleSubmit">确定</el-button>
                </div>
            </el-form>
        </el-drawer>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, UploadFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { storeToRefs, defineStore } from "pinia"
import P_store from "@store/supplierpro/index.js"


const P = P_store()
const { P_Form } = storeToRefs(P)
const R = useRouter()
const _G = defineStore('main', {})()
const _Id = ref(_G.M.GetId())

onMounted(() => {
    // P.Hp_GetAuditPlan(_Id.value)
})


const handleDrawerOpen = () => {
    // 初始化上传文件
    qualityForm.value.files = []
    if (uploadRef.value) {
        uploadRef.value.clearFiles()
    }
}

const examineOptions = [
    { value: '1', label: 'S' },
    { value: '2', label: 'A' },
    { value: '3', label: 'B' },
    { value: '4', label: 'C' },
    { value: '5', label: 'D' }
]


const showupload = ref(false)
const O_Add = (type) => {
    showDrawer.value = true
    showupload.value = true
    qualityForm.value = {
        supplierId: _Id.value
    }
}


const showDrawer = ref(false)
const editingId = ref(null)
const formTitle = computed(() => editingId.value ? '编辑质量计划' : '新增质量计划')

const qualityForm = ref({
    files: [],
    supplierId: _Id.value
})

const tableData = ref([])
const qualityFormRef = ref(null)

const uploadRef = ref(null)
const submitUpload = () => {
    uploadRef.value.submit()
}

const handleFileChange = (uploadFile, uploadFiles) => {
    qualityForm.value.files = uploadFiles.map(file => ({
        name: file.name,
        url: file.url || '',
        raw: file.raw
    }))
}

const handleUploadSuccess = (response, file, uploadFiles) => {
    const targetFile = qualityForm.value.files.find(f => f.name === file.name)
    if (targetFile) {
        targetFile.url = response.fileUrl
    }
    ElMessage.success('上传成功')
}

const handleUploadError = () => {
    ElMessage.error('上传失败')
}

const beforeUpload = (file) => {

    return true
}

const handleSubmit = () => {
    qualityFormRef.value?.validate((valid) => {
        if (valid) {
            console.log('质量计划表单数据：', qualityForm.value)
            showDrawer.value = false

            qualityForm.value.close = "NO"
            P.Hp_SevaAuditIssues(qualityForm.value)
            // TODO: 调用保存接口
        } else {
            ElMessage.error('请填写完整信息')
            return false
        }
    })
}

const handleEdit = (row) => {
    showupload.value = false
    editingId.value = row.id

    Object.assign(qualityForm.value, row)
    showDrawer.value = true
}

const handleDelete = (row) => {

    ElMessageBox.confirm('确认删除该计划？', '提示', {
        type: 'warning'
    }).then(() => {
        // TODO: 调用删除接口
        // ElMessage.success('删除成功')
        P.Hp_DelAuditIssues(row.auditIssuesId)
    })
}

const downloadFile = (file) => {
    // window.open(file.url)
    P.Hp_Download(file.uploadFileId)
}

const handleBack = () => {
    R.push('/supplierpro')
}


const handleExamine = (row) => {
    ElMessageBox.confirm('确认审核该问题？', '提示', {
        type: 'warning'
    }).then(async () => {
        //     qualityForm.value.close = "YES"
        // //    await P.Hp_SevaAuditIssues(qualityForm.value,true)
        await P.Hp_ExamineQuality('auditIssues', row.auditIssuesId)
    })
}

</script>

<style lang="less" scoped>
.button-group {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.drawer-form {
    padding: 20px;
}

.file-info {
    padding: 12px 16px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    transition: all 0.3s;
    color: #409eff;

    &:hover {
        border-color: #409eff;
        color: #79bbff;
    }

    .el-icon {
        font-size: 18px;
    }
}

.drawer-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20px;
    text-align: right;
    background: #fff;
    border-top: 1px solid #dcdfe6;
}

:deep(.upload-demo) {
    .el-upload {
        width: 100%;
    }

    .el-upload-dragger {
        width: 100%;
    }

    .el-upload__tip {
        line-height: 1.2;
        padding: 4px 0;
        color: #909399;
    }
}

.file-info {
    margin-bottom: 8px;

    &:last-child {
        margin-bottom: 0;
    }
}
</style>